﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace CleanToolkit.Tools
{
    public class XSerializer
    {
        /// <summary>
        /// Sérialisation générale
        /// <see cref="http://msdn.microsoft.com/fr-fr/library/c9ww5xa7(v=vs.80).aspx"/>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="overrideTypes"></param>
        /// <returns></returns>
        public static XDocument  Serialize<T>(T source, Type[] overrideTypes)
        {
            //Each object that is being overridden requires an XmlAttributes object. 
            XmlAttributes attrs = new XmlAttributes();

            // An XmlRootAttribute allows overriding the Orchestra class.
            XmlRootAttribute xmlRoot = new XmlRootAttribute();

            // Set the object to the XmlAttribute.XmlRoot property.
            attrs.XmlRoot = xmlRoot;

            // Create an XmlAttributeOverrides object.
            XmlAttributeOverrides attrOverrides =
            new XmlAttributeOverrides();

            // Add the XmlAttributes to the XmlAttributeOverrrides.
            foreach (Type type in overrideTypes)
            {
                attrOverrides.Add(type, attrs);
            }

            XDocument target = new XDocument();
            XmlSerializer s = new XmlSerializer(typeof(T), attrOverrides);
            System.Xml.XmlWriter writer = target.CreateWriter();
            s.Serialize(writer, source);
            writer.Close();
            return target;
        }
    }
}
